var express = require('express')
var router = express.Router()
var pool = require('../db')

// 执行SQL
router.post('/ext', (req, res) => {
  const { sql } = req.body
  pool.getConnection((error, connection) => {
    if(error) throw error
    connection.query(sql, [], (err, result) => {
      if (err) {
        res.json({ type: '2', result: err })
      } else {
        res.json({ type: '1', result })
      }
      //释放链接
      connection.release()
    })
  })
})

// 查询所有表结构
router.get('/query/tables', (req, res) => {
  const sql = `select table_name from information_schema.tables where table_schema=?`
  pool.getConnection((error,  connection) => {
    if(error) throw error
    connection.query(sql, ['sqleditor'], (err, result) => {
      if (err) {
        res.json({ type: '2', result: err })
      } else {
        res.json({ type: '1', result })
      }
      connection.release()
    })
  })
})

// 查询指定表的列
router.get('/query/field', (req, res) => {
  const { tname } = req.query
  const sql = 'SELECT COLUMN_NAME FROM information_schema. COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?'
  pool.getConnection((error, connection) => {
    if(error) throw error
    connection.query(sql, ['sqleditor', tname], (err, result) => {
      if (err) {
        res.json({ type: '2', result: err })
      } else {
        res.json({ type: '1', result })
      }
      connection.release()
    })
  })
})

module.exports = router;
